package com.lihui.utils;

import com.sun.mail.util.MailSSLSocketFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.PropertySource;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Component;

import javax.mail.Message;
import javax.mail.MessagingException;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;
import java.util.Properties;

/**
 * 电子邮件工具
 *
 * @author Skyvis-HUI
 * @date 2021/09/28
 */
@Component
@PropertySource(value = "classpath:application.properties",encoding = "UTF-8")
public class EmailTool {

    // 邮件主题
    @Value("${email.subject}")
    private String subject;

    // 邮件正文
    @Value("${email.content}")
    private String content;

    // 发件人邮箱
    @Value("${email.sender}")
    private String sender;

    // 授权码
    @Value("${email.password}")
    private String password;

    // 邮箱host
    @Value("${email.host}")
    private String host;

    @Async
    public void sendBirthDayWishes(String userName,String receiver) {
        sendMail(subject,userName+ content,receiver);
    }

    /**
     * 发送邮件
     * @param subject 主题
     * @param content 正文
     * @param receiver 收件人
     */
    public boolean sendMail(String subject, String content, String receiver) {
        Properties prop = new Properties();
        // 开启debug调试，以便在控制台查看
//        prop.setProperty("mail.debug", "true");
        // 设置邮件服务器主机名
        prop.setProperty("mail.host", host);
        // 发送服务器需要身份验证
        prop.setProperty("mail.smtp.auth", "true");
        // 发送邮件协议名称
        prop.setProperty("mail.transport.protocol", "smtp");
        Transport ts = null;
        try {
            // 开启SSL加密，否则会失败
            MailSSLSocketFactory sf = new MailSSLSocketFactory();
            sf.setTrustAllHosts(true);
            prop.put("mail.smtp.ssl.enable", "true");
            prop.put("mail.smtp.ssl.socketFactory", sf);
            // 创建session
            Session session = Session.getInstance(prop);
            // 通过session得到transport对象
            ts = session.getTransport();
            ts.connect(host, sender, password);
            // 创建邮件
            Message message = new MimeMessage(session);
            // 指明邮件的发件人
            message.setFrom(new InternetAddress(sender));
            InternetAddress[] sendTo = new InternetAddress[1];
            sendTo[0] = new InternetAddress(receiver);
            message.setRecipients(javax.mail.internet.MimeMessage.RecipientType.TO, sendTo);
            // 邮件的标题
            message.setSubject(subject);
            // 邮件的文本内容
            message.setContent(content, "text/html;charset=UTF-8");
            // 发送邮件
            ts.sendMessage(message, message.getAllRecipients());
            ts.close();
        } catch (Exception e) {
            if (ts != null) {
                try {
                    ts.close();
                } catch (MessagingException e1) {
                    e1.printStackTrace();
                }
            }
//            systemLogService.add("发送邮件失败", from + " 发送邮件给" + toList.toString());
            e.printStackTrace();
            return false;
        }
        return true;
    }
}
